<template>
  <el-form ref="loginForm" :model="loginForm" :rules="rules" @submit.native.prevent="handleLogin">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="loginForm.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="loginForm.password"></el-input>
    </el-form-item>
    <el-button type="primary" native-type="submit">登录</el-button>
    <el-button type="danger" @click="handleLogout">退出登录</el-button>
  </el-form>
</template>

<script>
export default {
  name: 'UserLogin',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    handleLogin() {
      if (this.loginForm.username && this.loginForm.password) {
        this.$store.dispatch('login', this.loginForm.username);
        this.$message.success('登录成功');
      } else {
        this.$message.error('登录失败：用户名或密码错误');
      }
    },
    handleLogout() {
      this.$store.dispatch('logout');
      this.$message.success('已退出登录');
    }
  }
};
</script>